//
//  XZHMovieStoryView.m
//  Piece
//
//  Created by Zeaho on 16/6/13.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "XZHMovieStoryView.h"
#import "Masonry.h"
#import "ZHNetworkHandler.h"
#import "XZHMovieStoryModel.h"
#import "UIImageView+WebCache.h"
#import "TFHpple.h"
@interface XZHMovieStoryView ()<UIWebViewDelegate>
@property (nonatomic, strong) NSMutableArray *storyDataSource;

@end

@implementation XZHMovieStoryView{
    UIView *storyView;
    UIImageView *userImageView;
    UILabel *usernameLabel;
    UILabel *dateLabel;
    UIWebView *_webView;
}

- (instancetype)initWithMovie_id:(NSString *)movie_id
{
    self = [super init];
    if (self) {
        self.movie_id = movie_id;
//        self.backgroundColor = [UIColor colorWithRed:0.99 green:0.99 blue:1.00 alpha:1.00];
        UILabel *movieStoryLabel = [[UILabel alloc] init];
        movieStoryLabel.text = @"电影故事";
        movieStoryLabel.font = [UIFont systemFontOfSize:12];
        movieStoryLabel.textColor = [UIColor colorWithRed:0.62 green:0.62 blue:0.62 alpha:1.00];
        [self addSubview:movieStoryLabel];
        [movieStoryLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10);
            make.top.equalTo(self).offset(0);
            make.width.equalTo(100);
            make.height.equalTo(44);
        }];
        
        UIButton *plotBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [plotBtn setImage:[UIImage imageNamed:@"unofficial_plot_normal"] forState:UIControlStateNormal];
        [self addSubview:plotBtn];
        [plotBtn makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-10);
            make.top.equalTo(self).offset(0);
            make.height.equalTo(44);
            make.width.equalTo(44);
        }];
        
        [self getMovieStoryDataByUrl];
        
        UIButton *allStoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [allStoryBtn setTitleColor:[UIColor colorWithRed:0.62 green:0.78 blue:0.91 alpha:1.00] forState:UIControlStateNormal];
        [allStoryBtn setTitle:@"全部电影故事" forState:UIControlStateNormal];
        allStoryBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [self addSubview:allStoryBtn];
        [allStoryBtn makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self);
            make.bottom.equalTo(self);
            make.width.equalTo(95);
            make.height.equalTo(25);
        }];
    }
    return self;
}


- (void)getMovieStoryDataByUrl {
    NSString *url = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/movie/%@/story/1/11583?platform=ios&uuid=5DA53470-1598-42FF-AB78-E2812C9D28AE&user_id=&version=v4.2.1", _movie_id];
//    NSLog(@"%@", _movie_id);
    [ZHNetworkHandler getDataByURLString:url WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        self.storyDataSource = [NSMutableArray array];
        NSArray *array = [[(NSDictionary *)result objectForKey:@"data"] objectForKey:@"data"];
        if (array.count != 0) {
            for (NSDictionary *dic in array) {
                XZHMovieStoryModel *storyModel = [[XZHMovieStoryModel alloc] initWithDic:dic];
                [self.storyDataSource addObject:storyModel];
            }
            XZHMovieStoryModel *storyModel = [[XZHMovieStoryModel alloc] init];
            storyModel = [_storyDataSource objectAtIndex:0];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12], NSFontAttributeName,nil];
            //得到新的frame
            CGRect newRect = [storyModel.content boundingRectWithSize:CGSizeMake(310, 8000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//            NSLog(@"%f",newRect.size.height);
            storyView = [[UIView alloc] init];
            storyView.backgroundColor = [UIColor colorWithRed:1.00 green:1.00 blue:1.00 alpha:1.00];
            [self addSubview:storyView];
            [storyView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self).offset(40);
                make.left.equalTo(self);
                make.height.equalTo(newRect.size.height + 40);
                make.width.equalTo(ScreenWidth);
            }];
            
            userImageView = [[UIImageView alloc] init];
            [storyView addSubview:userImageView];
            userImageView.layer.cornerRadius = 20;
            userImageView.layer.masksToBounds = YES;
            [userImageView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(storyView).offset(5);
                make.left.equalTo(15);
                make.width.equalTo(40);
                make.height.equalTo(40);
            }];
            [userImageView sd_setImageWithURL:[NSURL URLWithString:storyModel.userModel.web_url]];
            
            usernameLabel = [[UILabel alloc] init];
            usernameLabel.textColor = [UIColor colorWithRed:0.45 green:0.69 blue:0.96 alpha:1.00];
            usernameLabel.font = [UIFont systemFontOfSize:12];
            [storyView addSubview:usernameLabel];
            [usernameLabel makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(userImageView);
                make.left.equalTo(userImageView.right).offset(8);
                make.height.equalTo(40);
                make.width.equalTo(100);
            }];
            usernameLabel.text = storyModel.userModel.user_name;
            
            NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init] ;
            [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *inputDate = [inputFormatter dateFromString:storyModel.input_date];
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc]init];
            [outputFormatter setDateFormat:@"dd MMM,yyyy.EEE"];
            NSString *str = [outputFormatter stringFromDate:inputDate];
            
            
            dateLabel = [[UILabel alloc] init];
            dateLabel.textColor = [UIColor colorWithRed:0.74 green:0.74 blue:0.74 alpha:1.00];
            dateLabel.textAlignment = 2;
            dateLabel.font = [UIFont systemFontOfSize:11];
            [storyView addSubview:dateLabel];
            dateLabel.text = str;
            [dateLabel makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(usernameLabel).offset(-2);
                make.right.equalTo(storyView).offset(-10);
                make.width.equalTo(100);
                make.height.equalTo(40);
            }];
            
            _webView = [[UIWebView alloc] init];
            _webView.delegate = self;
            _webView.userInteractionEnabled = NO;
            [_webView setScalesPageToFit:YES];
            [storyView addSubview:_webView];
            [_webView makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(storyView).offset(40);
                make.left.equalTo(storyView).offset(63);
                make.right.equalTo(storyView).offset(-10);
                make.height.equalTo(newRect.size.height);
            }];
            NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", storyModel.content];
            [_webView loadHTMLString:htmlcontent baseURL:[NSURL URLWithString:url]];
//            UILabel *storyLabel = [[UILabel alloc] init];
//            storyLabel.numberOfLines = 0;
//            storyLabel.font = [UIFont systemFontOfSize:12];
//            [storyView addSubview:storyLabel];
//            [storyLabel makeConstraints:^(MASConstraintMaker *make) {
//                make.top.equalTo(storyView).offset(40);
//                make.left.equalTo(storyView).offset(63);
//                make.right.equalTo(storyView).offset(-10);
//                make.height.equalTo(newRect.size.height);
//            }];
//            
//            NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[[NSString stringWithFormat:@"<span style=\"font-size:14px;\">%@</span>", storyModel.content] dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
//            storyLabel.attributedText = attrStr;
//            NSData *data = [storyModel.content dataUsingEncoding:NSUTF8StringEncoding];
//            TFHpple *Hpple = [[TFHpple alloc] initWithHTMLData:data];
//            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//            NSArray *array =[Hpple searchWithXPathQuery:@"//body"]; //获取到为title的标题
//            
//            for (TFHppleElement *HppleElement in array) {
//                
//                NSLog(@"测试1的目的标签内容:-- %@",HppleElement.text);
//                
//            }
//            storyLabel.text = storyModel.content;
        }
        
        
        
    } WithFailure:^(NSError *error) {
        
    }];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //获取页面高度（像素）
    NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    float clientheight = [clientheight_str floatValue];
    //设置到WebView上
    webView.frame = CGRectMake(0, 0, self.frame.size.width, clientheight);
    //获取WebView最佳尺寸（点）
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    //获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    float height = [height_str floatValue];
    //内容实际高度（像素）* 点和像素的比
    height = height * frame.height / clientheight;
    [_webView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(height);
    }];
    self.StoryBlock(height);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
